//
//  DraClassicHeadView.swift
//  HomeDro
//
//  Created by mutou on 2023/5/17.
//

import UIKit

protocol DraClassicHeadViewDelegate: AnyObject {
    func didSelectTitleAt(_ index: Int)
}

class DraClassicHeadView: UIView {

    weak var delegate: DraClassicHeadViewDelegate?
    
    fileprivate var titles: [String] = []
    fileprivate var selectIndex = 0
    fileprivate var scrollView = UIScrollView()
    fileprivate var textWidths: [CGFloat] = []
    fileprivate var buttons: [UIButton] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    init(_ frame: CGRect, titles: [String], index: Int) {
        super.init(frame: frame)
        self.titles = titles
        self.selectIndex = index
        configSubViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func configSubViews() {
//        backgroundColor = .white
        addSubview(scrollView)
        scrollView.backgroundColor = .clear
        scrollView.bounces = false
        scrollView.frame = bounds
        scrollView.showsHorizontalScrollIndicator = false
                
        setupButtonsLayout()
    }

    fileprivate func setupButtonsLayout() {
        guard !titles.isEmpty else { return }
    
        // 将所有的宽度计算出来放入数组
        for title in titles {
            if title.count == 0 {
                textWidths.append(60)
                continue
            }
            let textW = title.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 40), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], context: nil).size.width
            textWidths.append(textW + 20)
        }
        
        // 按钮布局
        var upX: CGFloat = 10
        let subH = 44.0
        for index in 0..<titles.count {
            let subW = textWidths[index]
            let buttonRect = CGRect(x: upX, y: 11, width: subW, height: 28)
            let button = UIButton(type: .custom)
            button.frame = buttonRect
            button.tag = index
            button.setTitle(titles[index], for: .normal)
            button.addTarget(self, action: #selector(titleSelectIndex(_:)), for: .touchUpInside)
            button.layer.cornerRadius = 14
            button.clipsToBounds = true
            if self.selectIndex == index {
                button.backgroundColor = color("#FA6161")
                button.setTitleColor(.white, for: .normal)
                button.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
            }else{
                button.backgroundColor = color("#F5F6F8")
                button.setTitleColor(color("#333333"), for: .normal)
                button.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
            }
            scrollView.addSubview(button)
            buttons.append(button)
            upX = button.frame.origin.x + subW + 10
        }
        
        // 计算scrollView的contentSize
        // 最后多加了一个 layout.titleMargin， 这里要减去
        let contenSizeW = upX - 10 + 10 + 10.0
        scrollView.contentSize = CGSize(width: contenSizeW, height: subH)
//        let btn = buttons[selectIndex]
//        btn.setTitleColor(UIColor.black, for: .normal)
        self.setupSlierScrollToCenter(offsetX: self.scrollView.contentOffset.x, index: selectIndex, animated: false)
    }
    
    @objc fileprivate func titleSelectIndex(_ btn: UIButton)  {
        delegate?.didSelectTitleAt(btn.tag)
        if btn.tag == self.selectIndex {
            return
        }
        self.selectIndex = btn.tag
        
        //更改按钮背景颜色
        for index in 0..<buttons.count {
            if btn.tag == index {
                // 选中
                buttons[index].backgroundColor = color("#FA6161")
                buttons[index].setTitleColor(UIColor.white, for: .normal)
                buttons[index].titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
            }else{
                // 未选中
                buttons[index].backgroundColor = color("#F5F6F8")
                buttons[index].setTitleColor(color("#333333"), for: .normal)
                buttons[index].titleLabel?.font = UIFont.systemFont(ofSize: 13)
            }
        }
    }
    
    func updateData(_ titles: [String], index: Int) {
        if titles.isEmpty {
            return
        }
        for btn in buttons {
            btn.removeFromSuperview()
        }
        
        for subV in scrollView.subviews {
            subV.removeFromSuperview()
        }
        
        buttons.removeAll()
        textWidths.removeAll()
        
        self.titles = titles
        self.selectIndex = index
        setupButtonsLayout()
    }
   
    
    fileprivate func setupSlierScrollToCenter(offsetX: CGFloat, index: Int, animated: Bool)  {
        if scrollView.contentSize.width <= scrollView.frame.size.width {
            return
        }
        let currentButton = buttons[index]
        let btnCenterX = currentButton.center.x
        var scrollX = btnCenterX - scrollView.bounds.width * 0.5
        if scrollX < 0 {
            scrollX = 0
        }
        if scrollX > scrollView.contentSize.width - scrollView.bounds.width {
            scrollX = scrollView.contentSize.width - scrollView.bounds.width
        }
        scrollView.setContentOffset(CGPoint(x: scrollX, y: 0), animated: animated)
    }
    
}
